package views;


import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.drinkdevice.AddSelectGoodsActivity;
import com.example.administrator.drinkdevice.MainActivity;
import com.example.administrator.drinkdevice.R;

import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import Const.PublicDefine;
import Entity.ActivityResult;
import Enums.PayType;
import Helper.Log;
import Interface.IAsynCallBackListener;

public class Dialog_Member_Payment {
    public Context context;
    private Dialog dialog;
    private LinearLayout paymentLinear;
    private Button okBtn;
    private JSONObject memberCardPayment;
    private JSONArray goodsArray;
    private JSONObject memberInfo;
    private String discountPrice = "";
    private String salePrice = "";
    private PayType payType = PayType.PAYMENT_BALANCE;

    public Dialog_Member_Payment(final Context context, final JSONObject memberInfo, final JSONArray goodsArray, final IAsynCallBackListener callBack) {
        try {
            this.context = context;
            dialog = new Dialog(context);
            dialog.show();
            dialog.setCancelable(false);
            Window window = dialog.getWindow();
            window.setGravity(Gravity.CENTER);
            window.setContentView(R.layout.dialog_member_payment);
            window.setDimAmount(0);
            WindowManager.LayoutParams params = window.getAttributes();
            // 去除四角黑色背景
            window.setBackgroundDrawable(new BitmapDrawable());
            // 设置周围的暗色系数
            params.dimAmount = 0.5f;
            window.setAttributes(params);

            this.goodsArray = goodsArray;
            this.memberInfo = memberInfo;

            paymentLinear = dialog.findViewById(R.id.paymentLinear);
            okBtn = dialog.findViewById(R.id.ok);


            JSONObject balancePayment = new JSONObject();
            balancePayment.put("id", 0);
            balancePayment.put("storedcardName", "余额");
            balancePayment.put("value", memberInfo.getDouble("balance"));
            View_Member_Payment paymentView = new View_Member_Payment(context, balancePayment, new IAsynCallBackListener() {
                @Override
                public void onFinish(Object sender, Object data) {
                    selectPayment((View) sender, (JSONObject) data);
                }

                @Override
                public void onError(Object sender, Exception e) {

                }
            });
            memberCardPayment = balancePayment;
            saleGoodsCalculate(paymentView);
            paymentLinear.addView(paymentView);

            PublicDefine.webService.getMemberStoredCard(memberInfo.getString("id"), new IAsynCallBackListener() {
                @Override
                public void onFinish(Object sender, Object data) {
                    final String resStr = (String) data;
                    Message msg = new Message();
                    msg.obj = new IAsynCallBackListener() {
                        @Override
                        public void onFinish(Object sender, Object data) {
                            try {
                                JSONObject res = new JSONObject(resStr);
                                if (!res.getBoolean("success")) {
                                    throw new Exception(res.getString("message"));
                                }
                                JSONArray storedCards = res.getJSONArray("result");
                                for (int i = 0; i < storedCards.length(); i++) {
                                    JSONObject storedCard = storedCards.getJSONObject(i);
                                    View_Member_Payment paymentView = new View_Member_Payment(context,
                                            storedCard, new IAsynCallBackListener() {
                                        @Override
                                        public void onFinish(Object sender, Object data) {
                                            selectPayment((View_Member_Payment) sender, (JSONObject) data);
                                        }

                                        @Override
                                        public void onError(Object sender, Exception e) {

                                        }
                                    });
                                    paymentLinear.addView(paymentView);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                alert(e.getMessage());
                            }
                        }

                        @Override
                        public void onError(Object sender, Exception e) {

                        }
                    };
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onError(Object sender, Exception e) {

                }
            });

            okBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Map map = new HashMap();
                    map.put("discountPrice",discountPrice);
                    map.put("salePrice",salePrice);
                    callBack.onFinish(map, memberCardPayment);
                    dismiss();
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
            alert(e.getMessage());
        }
    }

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.obj instanceof IAsynCallBackListener) {
                ((IAsynCallBackListener) msg.obj).onFinish("", msg.arg1);
            }
        }
    };

    public void dismiss() {
        dialog.dismiss();
    }

    public void alert(final String info) {
        Message msg = new Message();
        msg.obj = new IAsynCallBackListener() {
            @Override
            public void onFinish(Object sender, Object data) {
                View toastRoot = ((MainActivity) context).getLayoutInflater().inflate(R.layout.my_toast, null);
                Toast toast = new Toast(context);
                toast.setView(toastRoot);
                TextView tv = (TextView) toastRoot.findViewById(R.id.TextViewInfo);
                tv.setText(info);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }

            @Override
            public void onError(Object sender, Exception e) {

            }
        };
        mHandler.sendMessage(msg);
    }

    //选择支付方式事件
    public void selectPayment(View v, JSONObject payment) {
        try {
            okBtn.setEnabled(false);
            memberCardPayment = payment;
            for (int i = 0; i < paymentLinear.getChildCount(); i++) {
                View_Member_Payment childView = (View_Member_Payment) paymentLinear.getChildAt(i);
                if (v == childView) {
                    saleGoodsCalculate(childView);
                } else {
                    childView.setCheck(false, "");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            alert(e.getMessage());
        }
    }

    //double转四舍五入字符串
    private String doubleCoverHalfUp(double num) {
        return new BigDecimal(num).setScale(2, BigDecimal.ROUND_HALF_UP) + "";
    }

    private void saleGoodsCalculate(final View_Member_Payment view) throws Exception {
        if (memberCardPayment.getInt("id") == 0) {
            payType = PayType.PAYMENT_BALANCE;
        } else {
            payType = PayType.PAYMENT_STORECARD;
        }
        PublicDefine.webService.saleGoodsCalculate(goodsArray, memberInfo.getString("id"), payType.ordinal(), new IAsynCallBackListener() {
            @Override
            public void onFinish(Object sender, Object data) {
                final String resStr = (String) data;
                Message msg = new Message();
                msg.obj = new IAsynCallBackListener() {
                    @Override
                    public void onFinish(Object sender, Object data) {
                        try {

                            JSONObject res = new JSONObject(resStr);
                            if (!res.getBoolean("success")) {
                                throw new Exception(res.getString("message"));
                            }
                            JSONObject resData = res.getJSONObject("result");
                            discountPrice = doubleCoverHalfUp(resData.getJSONObject("discount").getDouble("cash") / 100);
                            salePrice = doubleCoverHalfUp(resData.getDouble("bisCash") / 100);
                            String payCashInfo = "(支付¥" + salePrice + "，优惠¥" + discountPrice + ")";
                            view.setCheck(true, payCashInfo);
                            okBtn.setEnabled(true);
                        } catch (Exception e) {
                            e.printStackTrace();
                            alert(e.getMessage());
                        }
                    }

                    @Override
                    public void onError(Object sender, Exception e) {

                    }
                };
                mHandler.sendMessage(msg);
            }

            @Override
            public void onError(Object sender, Exception e) {
                e.printStackTrace();
                alert(e.getMessage());
            }
        });
    }

    public boolean isShowing() {
        return dialog.isShowing();
    }
}
